/*
 *
 *  Copyright (C) 2010 GSyC/LibreSoft, Universidad Rey Juan Carlos.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Raúl Román López <rroman@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class IPlocation {
	
	public static int[] makePetition(){
		String url = "http://www.google.com/loc/json";
		String data = petitionConstructor();
		
		int[] coords = responseParser(send(url, data));
		
		return coords;
	}
	
	private static int[] responseParser(String response){
		String coord;
		int[] coords = new int[3];
		
		try{
			coord = response.split("latitude")[1].split(":")[1].split(",")[0];
			coords[0] = (int)(Float.parseFloat(coord) * 1E6);

			coord = response.split("longitude")[1].split(":")[1].split(",")[0];
			coords[1] = (int)(Float.parseFloat(coord) * 1E6);

			coord = response.split("accuracy")[1].split(":")[1].split("\\.")[0];
			coords[2] = Integer.parseInt(coord);
		}catch(Exception e){
			return null;
		}
		
		return coords;
	}
	
	private static String petitionConstructor(){
		String request;
		
		request = "{'host': '_null_.localdomain', " +
				"'radio_type': 'unknown'," +
				"'request_address': false, " +
				"'version': '1.1.0'}";
		
		return request;
	}
	

	public static String send(String Url, String data){
		String responseData, line;
		
		try {
			URL url = new URL(Url);
			try {
				URLConnection urlConn = (HttpURLConnection) url.openConnection();
				urlConn.setDoOutput (true);
				OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream());
				out.write (data);
				out.flush();
				
				BufferedReader in = new BufferedReader(
						new InputStreamReader(
								urlConn.getInputStream()));
				//recoger lo que lee en responseData
				responseData = "";
				while ((line = in.readLine())!=null){
					responseData += line;
				}
				
				out.close();
				in.close();
				
				return responseData;
				
			} catch (IOException e) {
				return e.toString();
			}
		} catch (MalformedURLException e) {
			return e.getMessage();
		}
	}
}